<?php
defined('IN_PHPCMS') or exit('No permission resources.');

error_reporting(E_ERROR);
require_once "classes/lib/WxPay.Api.php";
require_once "classes/WxPay.NativePay.php";
require_once 'classes/log.php';

require_once 'classes/phpqrcode/phpqrcode.php';
/**
 *购物前台
 */
class shop
{
  protected $db, $siteid;
  /**
   * shop类构造函数，初始化常用参数
   */
  function __construct()
  {
    $this->db = pc_base::load_model('content_model');
    $this->shop_db = pc_base::load_model('shop_model');
    //定义站点ID常量，选择模版使用
    $this->siteid = isset($_GET['siteid']) ? intval($_GET['siteid']) : get_siteid();
    define("SITEID", $this->siteid);

    //读取配置
    // $setting = new_html_special_chars(getcache('guestbook', 'commons'));
    // $this->set = $setting[SITEID];
  }

  /**
   * 购物入口函数
   * @return [template] [shop index]
   */
  public function init()
  {
    // 获取货物信息
    $catid = intval($_GET['catid']);
		$id = intval($_GET['id']);

		if(!$catid || !$id) showmessage(L('information_does_not_exist'),'blank');
		// $siteids = getcache('category_content','commons');
		// $siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$this->siteid,'commons');


		if(!isset($CATEGORYS[$catid]) || $CATEGORYS[$catid]['type']!=0) showmessage(L('information_does_not_exist'),'blank');
		$this->category = $CAT = $CATEGORYS[$catid];
		$this->category_setting = $CAT['setting'] = string2array($this->category['setting']);
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];

		$MODEL = getcache('model','commons');
		$modelid = $CAT['modelid'];

		$tablename = $this->db->table_name = $this->db->db_tablepre.$MODEL[$modelid]['tablename'];
		$product = $this->db->get_one("`id` = '$id'");

    // 生成订单号，商家系统内部订单号只要唯一即可
    // $orderSN = WxPayConfig::MCHID . serial_number();  //自定义订单生成
    $orderSN = WxPayConfig::MCHID.date("YmdHis");  //微信范例订单生成
    // 生成二维码地址
    $url = urlencode($this->WxPay($product,$orderSN));

    include template('shop','index');
  }

  /**
   * 商品下单函数
   * @return [type] [description]
   */
  public function post()
  {
    // 数据检测
    if(!$_POST) die('MF001');
    if(!$this->checkField(['username','phone','address','ordersn'])) die('MF002');

    // 数据项写入前格式化
    $data['ordersn'] = $_POST['ordersn'];
    $data['siteid'] = SITEID;
    $data['username'] = $_POST['username'];
    $data['phone'] = $_POST['phone'];
    $data['address'] = $_POST['address'];
    $data['zipcode'] = $_POST['zipcode'];
    $data['goodsid'] = $_GET['id'];
    $data['goodscatid'] = $_GET['catid'];
    $data['goodsname'] =  $_POST['goodsname'];
    $data['goodsprice'] = $_POST['goodsprice'];
    $data['content'] = $_POST['content'];
    $data['ip'] = $_SERVER["REMOTE_ADDR"];
    $data['addtime'] = time();

    // 判断订单数据是否写入过
    $where .= " `ordersn`='".$_POST['ordersn']."' ";
    $result = $this->shop_db->get_one($where);
    if($result==''){
      // 未写入，则新增
      $this->shop_db->insert($data);
    }
    else {
      // 已写入，则修改，失败返回001
      if(!$this->shop_db->update($data, array('ordersn' => $_POST['ordersn']))) die('MF001');
    }

    die('MF000');
  }

  /**
   * 二维码生成函数
   * @param  [type] $url [description]
   * @return [type]      [description]
   */
  public function qrcode()
  {
    $url = urldecode($_GET["data"]);
    QRcode::png($url);
  }

  public function search(){
    //获取siteid
    $siteid = isset($_REQUEST['siteid']) && trim($_REQUEST['siteid']) ? intval($_REQUEST['siteid']) : 1;
    $SEO = seo($siteid);
    $CATEGORYS = getcache('category_content_'.$siteid,'commons');

    if ( isset($_POST['ordersn']) && trim($_POST['ordersn'])!='' ) {
      #查询
      $sn = safe_replace(trim($_POST['ordersn']));
      $sn = new_html_special_chars(strip_tags($sn));
      $sn = str_replace('%', '', $sn);	//过滤'%'，用户全文搜索

      $data = $this->shop_db->get_one("`ordersn` = '$sn'");
      if ($data['status']) {
        if ($data['passed']) {
          $temp = ($data['trackingid']!='') ? '已发货' : '已备货';
        }
        else {
          $temp = '已支付';
        }
      }
      else {
        $temp = '未支付';
      }
    }
    include	template('shop','search');
  }


  /**
   * 微信订单查询
   * @return [type] [description]
   */
  public function pollingOrder()
  {
    $sn = $_POST["orderSN"];
    // 查询订单是否支付
    $input = new WxPayOrderQuery();
		$input->SetOut_trade_no($sn);
		$result = WxPayApi::orderQuery($input);
		// Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("trade_state", $result) && array_key_exists("result_code", $result) && $result["trade_state"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
      // 输出成功标志
			echo 1;
      // 数据项写入前格式化
      $data['status'] = true;
      $data['tradeno'] = $result['transaction_id'];

      $where .= " `ordersn`='".$sn."' ";
      $result = $this->shop_db->get_one($where);
      // 判断订单数据是否存在
      if ($result != '') {
        // 更新订单状态
        $this->shop_db->update($data, array('ordersn' => $sn));
      }
		}
    else {
      echo 0;
    }
  }

  public function success()
  {

    include template('shop','success');
  }

  /**
   * 统一下单函数
   * @param [type] $product [description]
   * @param [type] $orderSN [description]
   */
  protected function WxPay($product,$orderSN)
  {
    $notify = new NativePay();
    $input = new WxPayUnifiedOrder();

    $input->SetBody("华昱药业-" . $product['title']);
    $input->SetAttach("网站购物");
    $input->SetOut_trade_no($orderSN); //本地订单号
    $input->SetTotal_fee((float)$product['price'] * 100);
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 3000));
    $input->SetGoods_tag($product['keywords']);
    $input->SetNotify_url("http://test.goldseasonpharma.com/wechat/pay/notify.php");
    $input->SetTrade_type("NATIVE");
    $input->SetProduct_id((string)$product['catid'] ."-". (string)$product['id']);
    $result = $notify->GetPayUrl($input);
    // var_dump($result);
    $url2 = $result["code_url"];
    // die($url2);
    return $url2;

  }

  /**
   * 字段为空检查
   * @param  [type] $fields [description]
   * @return [type]         [description]
   */
  protected function checkField($fields)
  {
    foreach ($fields as $key => $value) {
      if(!isset($_POST[$value]) || trim($_POST[$value])=='') return false;
    }
    return true;
  }
}
?>
